<html>
<head>

<title>Groovy Goodness: Implicit Method doCall in Closure</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Implicit Method doCall in Closure</h3>

<div class="post">
<p>After reading <a href="http://groovy.dzone.com/articles/mixing-dynamic-and-static-code-0">Mixing dynamic and static code in Groovy</a> I learned about the implicit method available in a closure: <code>doCall()</code>. This method corresponds to the arguments and body of the closure. If we invoke a closure with the <code>call()</code> or the unnamed <code>()</code> syntax the <code>doCall()</code> method is invoked. We can use this method to run the closure from within the closure.</p>
<pre class="brush:groovy">
def sizeList = { list, counter = 0 ->
    if (list.size() == 0) {
        counter
    } else {
        doCall(list.tail(), counter + 1)  // Call closure self.
    }
}

assert 5 == sizeList([1,2,3,4,5])
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>